<?php
// +----------------------------------------------------------------------
// | Amicool-MVC [ Dynamic Flexible Agile Devlepment]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2020 http://amicool.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 郡笑笙 <iamzjs@126.com>
// +----------------------------------------------------------------------
require 'ConnDB.php';
require APP_ROOT.'Common/conf/config.php';
class Model{
	private $conn;
	function __Construct(){
		$this->conn = new ConnDB(DB_TYPE,DB_HOST,DB_USER,DB_PWD,DB_DBNAME,DB_CHARSET);
	}
	function _fetchAll($mod,$condition='where 1=1'){
		$sql = "select * from $mod $condition";
		return $this->conn->query($sql);
	}
	function _fetchOne($mod,$id,$val){
		$sql = "select * from $mod where $id='$val'";
		return $this->conn->query($sql);
	}
	function _add($mod,$data){
		$keys = implode(',',array_keys($data));
		$values = implode('\',\'', array_values($data));
		$sql = "insert into ".$mod;
		$sql.="(".$keys.") values('".$values."')";
		$result = mysql_query($sql);
		if($result===FALSE){
			return 0;
		}
		else{
			return mysql_insert_id();
		}
	}

	/**
	 * MYSQL更新操作
	 * @param array $data
	 * @param string $mod
	 * @param string $where
	 * @return number|boolean
	 */
	function _update($mod,$data,$where=null){
	    foreach ($data as $key=>$val){
	        $sets.=$key."='".$val."',";
	    }
	    $sets=rtrim($sets,','); //去掉SQL里的最后一个逗号
	    $where=$where==null?'':' WHERE '.$where;
	    $sql="UPDATE {$mod} SET {$sets} {$where}";
	    $res=mysql_query($sql);
	    if ($res){
	        return mysql_affected_rows();
	    }else {
	        return false;
	    }
	}


	/**
	 * 删除记录的操作
	 * @param string $table
	 * @param string $where
	 * @return number|boolean
	 */
	function _delete($mod,$where=null){
	    $where=$where==null?'':' WHERE '.$where;
	    $sql="DELETE FROM {$mod}{$where}";
	    $res=mysql_query($sql);
	    if ($res){
	        return mysql_affected_rows();
	    }else {
	        return false;
	    }
	}
	/**取得结果集中的记录的条数
	 * @param string $sql
	 * @return number|boolean
	 */
	function _getTotalRows($sql){
	    $result=mysql_query($sql);
	    if($result){
	        return mysql_num_rows($result);
	    }else {
	        return false;
	    }
	    
	}

	/**释放结果集
	 * @param resource $result
	 * @return boolean
	 */
	function  freeResult($result){
	    return  mysql_free_result($result);
	}



	/**断开MYSQL
	 * @param resource $link
	 * @return boolean
	 */
	function close($link=null){
	    return mysql_close($link);
	}


}
?>